<?php
/**
 * Zead
 *
 * LICENSE	
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/bsd-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to eu@marcelomx.com so we can send you a copy immediately.
 *
 * @category   Zead
 * @author     Marcelo Rodrigues Gonzaga <eu@marcelomx.com>
 * @copyright  Copyright (c) 2008 Marcelo Rodrigues Gonzaga
 * @link       http://code.google.com/p/zead 
 * @license    http://www.opensource.org/licenses/bsd-license.php     New BSD License
 *
 **/


/** @see Zead_Player_Plugin_Abstract **/
require_once 'Zead/Player/Plugin/Abstract.php';

/** @see Zead_Auth **/
require_once 'Zead/Auth.php';

/**
 * @category   Zead
 * @package    Zead_Player
 * @package    Zead_Player_Plugin
 * @copyright  Copyright (c) 2008 Marcelo Rodrigues Gonzaga 
 * @license    http://www.opensource.org/licenses/bsd-license.php     New BSD License 
 */
class Zead_Player_Plugin_Auth extends Zead_Player_Plugin_Abstract 
{
	/**
	 * Registro de verificação se a autorização já foi executada.
	 * @var boolean
	 */
	protected $_preDispatched = false;

	/**
	 * Executando o plugin antes da execução da ação propriamente dita.
	 * 
	 */
	public function preDispatch() 
	{
		if ($this->_preDispatched !== false)
			return;

		$this->_preDispatched = true;
		
		// Recuperando o parametro com o identificador
		$identity  = $this->getRequest()->getIdentity();
	
		// Recuperando a instancia do autenticador
		$auth = Zead_Auth::getInstance();
		
		// Setando o storage
		$storage = new Zend_Auth_Storage_Session(Zend_Auth_Storage_Session::NAMESPACE_DEFAULT, $identity);
		$auth->setStorage($storage);
		$credential = (array) $storage->read();
			
		// Recuperando o adaptador
		require_once 'Zead/Auth/Adapter/Session.php';
		$adapter = new Zead_Auth_Adapter_Session();
		$adapter->setIdentity($identity)
			->setCredential($credential);

		// Autenticando
		$result = $auth->authenticate($adapter);

		// Se no validou, recupera o resultado		
		if ($result->isValid()) {
			
			// Aqui comandos em caso de sucesso na validao
			$player = $this->getPlayer();			
			$player->setParam('credential', $adapter->getCredentialNormalized());
			return;
		}
		
		// Se codigo zero e o arquivo eh o log, entaum gera um novo processo.	
		if ($result->getCode() == 0 && $this->getRequest()->isAuth()) {
			$id = Zead_Auth::generateId();
			$storage = new Zend_Auth_Storage_Session(Zend_Auth_Storage_Session::NAMESPACE_DEFAULT, $id);
			$storage->write($adapter->setIdentity($id)->generateCredential());			
			$_GET['id'] = $id;
				
			// Redirecionando
			$this->getResponse()
				->setRedirect('index.php?'. http_build_query($this->getRequest()->getQuery(), '', '&'))
				->sendResponse();
				
			return;
		}			
		// Avaliando o cdigo do erro, e redirecionando para o endereo do erro.	
		$this->getResponse()
			->setRedirect('error_0'. (int) $result->getCode() . '.php')
			->sendResponse();
	}

		
	public function postDispatch() 
	{
		// Collect the garbage session and clean all invalid or old sessions

	}	
}

